package com.jyw.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.EventBusTypes;
import com.jyw.service.GeTuiPushService;
import com.jyw.service.GetIntentService;

import java.io.IOException;
import java.util.regex.Pattern;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/2
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvYzm, tvGo;
    private EditText mEditPhoneNum, mEditYzm;
    private TimeCount mTimer;
    private String phoneNum;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        // com.getui.demo.DemoPushService 为第三方自定义推送服务
        PushManager.getInstance().initialize(getApplicationContext(), GeTuiPushService.class);

        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(getApplicationContext(), GetIntentService.class);
        setContentView(R.layout.activity_login);

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        tvYzm = (TextView) findViewById(R.id.tv_yzm);
        tvGo = (TextView) findViewById(R.id.tv_go);
        mEditPhoneNum = (EditText) findViewById(R.id.edit_phonenum);
        mEditYzm = (EditText) findViewById(R.id.edit_yzm);
        tvYzm.setOnClickListener(this);
        tvGo.setOnClickListener(this);

        mTimer = new TimeCount(60000, 1000);//构造CountDownTimer对象
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_yzm:
                clickKapcher();
                break;
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.tv_go:
                phoneNum = mEditPhoneNum.getText().toString();
                if (!TextUtils.isEmpty(phoneNum)) {
                    Pattern p1 = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
                    if (!p1.matcher(phoneNum).matches()) {
                        Toast.makeText(LoginActivity.this, "电话号码有误", Toast.LENGTH_SHORT).show();
                    } else {
                        go();
                    }
                } else {
                    Toast.makeText(this, "电话不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void go() {
        String cid = getPrefs().getString("client_id", "");
        if (cid.equals("")) {
            Toast.makeText(LoginActivity.this, "错误：client_id为空", Toast.LENGTH_LONG).show();
            return;
        }
        Request request = new Request.Builder().
                url(Server.LOGIN + "?phone_data=" + phoneNum +
                        "&token_data=" + cid + "&clientid_data=" + cid + "&os=Android&code="
                        + mEditYzm.getText()).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(LoginActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.body().string().equals("1")) {
                    OkHttpManager.backgroundThreadShortToast(LoginActivity.this, "登陆成功");
                    getPrefs().edit().putString("phone", phoneNum).putString("code", mEditYzm.getText().toString()).apply();
                    EventBus.getDefault().post(new EventBusTypes.LoginSuccess());
                    finish();
                } else {
                    OkHttpManager.backgroundThreadShortToast(LoginActivity.this, "登陆出错");
                }
            }
        });
    }


    protected void clickKapcher() {
        phoneNum = mEditPhoneNum.getText().toString();
        if (!TextUtils.isEmpty(phoneNum)) {
            Pattern p1 = Pattern.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$");
            if (!p1.matcher(phoneNum).matches()) {
                Toast.makeText(LoginActivity.this, "电话号码有误", Toast.LENGTH_SHORT).show();
            } else {
                sendCode();
            }
        } else {
            Toast.makeText(this, "电话不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendCode() {
        Request request = new Request.Builder().
                url(Server.SEND_CODE + "?phone=" + phoneNum).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(LoginActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                OkHttpManager.backgroundThreadShortToast(LoginActivity.this, "已发送");
                mTimer.start();
            }
        });
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            tvYzm.setText("重新获取");
            tvYzm.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            tvYzm.setClickable(false);
            tvYzm.setText(millisUntilFinished / 1000 + "秒");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(EventBusTypes.ObtainClientId type) {
        getPrefs().edit().putString("client_id", ((EventBusTypes.ObtainClientId) type).cid).apply();
    }

}
